package com.test.sh.dao.impl;

import com.test.sh.dao.BookShopDao;
import com.test.spring.transaction.xml.BookStockException;
import com.test.spring.transaction.xml.UserAccountException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2018-10-06 17:21
 */
@Repository
public class BookShopDaoImpl implements BookShopDao {

    @Autowired
    private SessionFactory sessionFactory;

    // 不推荐使用HibernateTemplate和HibernateSupport
    // 因为这样会导致Dao和Spring的API进行耦合
    // 可移植性变差

    //获取和当前线程绑定的session
    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public double findBookPriceByIsbn(String isbn) {
        String hql = "SELECT b.price FROM Book b WHERE b.isbn=?";
        Query query = getSession().createQuery(hql).setString(0, isbn);
        return (double) query.uniqueResult();
    }

    @Override
    public void updateBookStock(String isbn) {
        //验证书的库存是否充足
        String hql2 = "SELECT b.stock FROM Book b WHERE b.isbn=?";
        int stock = (int) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();
        if (stock <= 0) {
            throw new BookStockException("书的库存不足");
        }

        String hql = "UPDATE Book b SET b.stock=b.stock-1 WHERE b.isbn=?";
        getSession().createQuery(hql).setString(0, isbn).executeUpdate();
    }

    @Override
    public void updateUserAccount(String userName, double price) {
        //验证余额是否足够
        String hql = "SELECT a.balance FROM Account a WHERE a.userName=?";
        double balance = (double) getSession().createQuery(hql).setString(0, userName).uniqueResult();
        if (balance < price) {
            throw new UserAccountException("余额不足");
        }
        String hql2 = "UPDATE Account a SET a.balance = a.balance-? WHERE a.userName=?";
        getSession().createQuery(hql2).setDouble(0, price).setString(1, userName).executeUpdate();
    }
}
